/**
 * 保养工单
 */

import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { useHistory } from 'react-router-dom';
import {
    Button,
    message,
    // Input,
    Select,
    DatePicker,
    Form,
    Card,
    Tabs,
    Modal,
    // Typography,
} from 'antd';

import { get } from '../../axios/http';
import { convertRes2Blob, BasicTable } from '../../utils/x.js';

import { euqApplicationName } from '../../config';
const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs;

/**
 * 搜索表单
 */
function MaintenanceWorkOrder2SearchForm({ form, form: { getFieldDecorator }, onSubmit }) {
    const handleSubmit = useCallback((e) => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            onSubmit && onSubmit(values);
        });
    }, [onSubmit]);

    return (
        <Form layout="inline" onSubmit={handleSubmit}>
            <Form.Item label="创建时间">
                {getFieldDecorator('queryTime')(
                    <RangePicker />
                )}
            </Form.Item>
            <Form.Item label="保养状态">
                {getFieldDecorator('maintainStatus', {
                    initialValue: null,
                })(
                    <Select style={{ width: 150 }}>
                        <Option value={null}>全部</Option>
                        <Option value={0}>保养中</Option>
                        <Option value={1}>已完成</Option>
                        <Option value={2}>待保养</Option>
                    </Select>
                )}
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">搜索</Button>
            </Form.Item>
        </Form>
    );
}

/**
 * 表单列表
 */
function MaintenanceWorkOrder2Table({ data, selectedKeys, pagination, loading, onEvent }) {
    const handleDetailClick = useCallback((e) => {
        e.preventDefault();
        const id = Number(e.currentTarget.getAttribute('data-id'));
        onEvent && onEvent({ type: 'EDIT_ITEM', id });
    }, [onEvent]);

    const tableColumns = [
        {
            title: '操作',
            render: (text, row, index) => {
                return (
                    <>
                        <a href="#" data-id={row.id} onClick={handleDetailClick}>详细</a>
                    </>
                );
            },
        },
        {
            title: '保养单号',
            dataIndex: 'maintainCode',
        },
        {
            title: '保养状态',
            dataIndex: 'maintainStatus',
            render: (text) => {
                switch (text) {
                    case 0:
                        return '保养中';
                    case 1:
                        return '已完成';
                    case 2:
                        return '待保养';
                }
            }
        },
        {
            title: '设备编号',
            dataIndex: 'equipmentCode',
        },
        {
            title: '设备名称',
            dataIndex: 'equipmentName',
        },
        {
            title: '计划序号',
            dataIndex: 'planId',
        },
        {
            title: '规格型号',
            dataIndex: 'equipmentSpecsModel',
        },
        {
            title: '使用部门',
            dataIndex: 'equipmentDepart',
        },
        {
            title: '保养开始时间',
            dataIndex: 'maintainStartTime',
        },
        {
            title: '保养结束时间',
            dataIndex: 'maintainEndTime',
        },
        {
            title: '保养用时',
            dataIndex: 'wastedTime',
        },
        {
            title: '保养费用',
            dataIndex: 'maintainCost',
        },
    ];
    const tableRowSelection = {
        selectedRowKeys: selectedKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            onEvent({ type: 'UPDATE_SELECTED', keys: selectedRowKeys, rows: selectedRows });
        },
    };

    return (
        <BasicTable
            rowKey="id"
            dataSource={data}
            columns={tableColumns}
            rowSelection={tableRowSelection}
            pagination={pagination}
            loading={loading} />
    );
}


/**
 * 主组件
 */
function MaintenanceWorkOrder2() {
    const history = useHistory();

    const [data1, setData1] = useState([]);
    const [data1Query, setData1Query] = useState({});
    const [pagination, setPagination] = useState({});
    const [isData1Loading, setIsData1Loading] = useState(false);
    const [selected, setSelected] = useState({ key: [], row: [] });

    const fetchData = useCallback((params = {}, exact = false) => {
        setData1Query(exact ? params : prev => ({
            ...prev,
            ...params,
        }));
    }, []);

    const exportExcel = useCallback((list = []) => {
        return (async () => {
            try {
                const reqData = selected.key.map(item => `idList=${item}`).join('&');
                const url = list.length === 0 ? euqApplicationName + '/equipmentMaintain/exportEquipmentMaintainExcel' : `${euqApplicationName}/equipmentMaintain/exportEquipmentMaintainExcel?${reqData}`;
                const res = await get(url, { responseType: 'blob' });
                convertRes2Blob(res, '保养工单');
            } catch (err) {
                Modal.error({
                    title: '发生了错误',
                    content: err.message,
                });
                console.error(err);
            }
        })();
    }, []);

    // 表格1事件
    const handleTableEvent = useCallback((e) => {
        switch (e.type) {
            case 'EDIT_ITEM': {
                history.push(`/MaintenanceWorkOrderDetail/${e.id}`);
                break;
            }
            case 'UPDATE_SELECTED': {
                setSelected({ key: e.keys, row: e.rows });
                break;
            }
        }
    }, [data1]);

    // 搜索工单提交
    const handleSearchFormSubmit = useCallback((values) => {
        const reqData = {
            ...values,
        };
        if (values.queryTime && values.queryTime.length > 0) {
            reqData.startTime = values.queryTime[0].format('YYYY-MM-DD');
            reqData.endTime = values.queryTime[1].format('YYYY-MM-DD');
        }
        delete reqData.queryTime;
        // console.log('reqdata', reqData); return;
        fetchData(reqData, true);
    }, []);

    // 操作按钮点击
    const handleExtraClick = useCallback((e) => {
        const action = e.currentTarget.getAttribute('data-action');
        switch (action) {
            case 'add': {
                history.push('/MaintenanceWorkOrderDetail');
                break;
            }

            case 'delete': {
                if (selected.key.length < 1) {
                    Modal.info({
                        title: '需要至少选择一个项目',
                    });
                    return;
                }
                Modal.confirm({
                    title: '你确定要删除这些项目吗？',
                    onOk() {
                        (async () => {
                            try {
                                const reqData = {
                                    ids: selected.key.join(','),
                                };
                                // console.log(reqData); return;
                                const res = await get(`${euqApplicationName}/equipmentMaintain/deleteEquipmentMaintain/${reqData.ids}`);
                                message.info('删除成功');
                                setSelected({ key: [], row: [] });
                                fetchData();
                            } catch (err) {
                                Modal.error({
                                    title: '发生了错误',
                                    content: err.message,
                                });
                            }
                        })();
                    },
                });
                break;
            }

            case 'export': {
                if (selected.key.length < 1) {
                    Modal.confirm({
                        title: '当前没有选择项目，将会导出所有数据。是否继续？',
                        onOk() {
                            exportExcel();
                        },
                    });
                } else {
                    exportExcel(selected.key);
                }
            }
        }
    }, [selected]);

    const tabExtraContent = (
        <div>
            <Button icon="edit" type="primary" style={{ marginLeft: 5 }} data-action="add" onClick={handleExtraClick}>添加工单</Button>
            <Button icon="delete" type="danger" style={{ marginLeft: 5 }} data-action="delete" onClick={handleExtraClick}>删除</Button>
            <Button icon="arrow-down" style={{ marginLeft: 5, marginRight: 5 }} data-action="export" onClick={handleExtraClick}>导出</Button>
        </div>
    );

    const SearchForm = useMemo(() => {
        return Form.create()(MaintenanceWorkOrder2SearchForm);
    }, []);

    useEffect(() => {
        (async () => {
            // console.log('query:', data1Query);
            setIsData1Loading(true);
            try {
                const res = await get(euqApplicationName + '/equipmentMaintain/findEquipmentMaintain', { params: data1Query });
                setData1(res.data);
                setPagination({
                    current: res.pageNum,
                    pageSize: res.pageSize,
                    total: res.total,
                    onChange(page) {
                        setData1Query(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                });
            } catch (err) {}
            setIsData1Loading(false);
        })();
    }, [data1Query]);

    return (
        <>
            <Card size="small" style={{ marginBottom: 10 }}>
                <SearchForm onSubmit={handleSearchFormSubmit} />
            </Card>
            <Card size="small">
                <Tabs tabBarExtraContent={tabExtraContent}>
                    <TabPane tab="保养工单" key={1}>
                        <MaintenanceWorkOrder2Table data={data1} selectedKeys={selected.key} pagination={pagination} loading={isData1Loading} onEvent={handleTableEvent} />
                    </TabPane>
                </Tabs>
            </Card>
        </>
    );
}

export default MaintenanceWorkOrder2;
